package logic

import (
	"cart_srv/cache"
	"cart_srv/models"
	"context"
	"errors"
	"fmt"

	"cart_srv/cart"
	"cart_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cart.AddCartRequest) (*cart.AddCartResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var u models.User
	var g models.Goods

	if err = u.GetUserById(in.UserId); err != nil {
		logx.Error("用户信息获取失败")
		return nil, errors.New("用户信息获取失败")
	}
	if u.ID == 0 {
		return nil, errors.New("该用户不存在")
	}

	if err = g.GetGoodsById(in.GoodsId); err != nil {
		logx.Error("商品信息获取失败")
		return nil, errors.New("商品信息获取失败")
	}
	if g.ID == 0 {
		return nil, errors.New("该商品不存在")
	}

	if g.Stock < in.Num {
		return nil, errors.New("商品库存不足")
	}

	if cache.IsExistCart(in.UserId, in.GoodsId) {
		fmt.Println("购物车种存在该商品")

		err = cache.HIncrNum(in.UserId, in.GoodsId, in.Num)
		if err != nil {
			return nil, errors.New("商品数量累加失败")
		}
	} else {
		fmt.Println("购物车种不存在该商品")

		goodsMap := map[string]interface{}{
			"user_id":     in.UserId,
			"goods_id":    in.GoodsId,
			"goods_title": g.Title,
			"goods_price": g.Price,
			"num":         in.Num,
		}
		if err = cache.AddCart(in.UserId, in.GoodsId, goodsMap); err != nil {
			logx.Error("添加入购物车失败")
			return nil, errors.New("添加入购物车失败")
		}
	}
	return &cart.AddCartResponse{
		UserId: in.UserId,
	}, nil
}
